"""
word 转pdf
"""
import fitz
import os
from PIL import Image


def get_path():
    pngdir = os.path.join(os.getcwd(), "jpg_picture")
    filename_list = os.listdir(pngdir)
    jpgname_list = [
        filename for filename in filename_list if filename.endswith((".png", ".PNG"))]

    for jpgname in jpgname_list:
        pngname = os.path.splitext(jpgname)[0] + ".jpg"
        # 拼接 路径和文件名
        jpgpath = os.path.join(pngdir, jpgname)
        pngpath = os.path.join(pngdir, pngname)
        # yield 生成器
        yield jpgpath, pngpath


def convert_png():
    for jpgpath, pngpath in get_path():
        try:
            im = Image.open(jpgpath)
            im.save(pngpath)
            os.remove(jpgpath)
            print(jpgpath + "-->转换完成")
        except Exception as e:
            print(e)


def conver_to_picture():
    path = os.getcwd()
    filename_list = os.listdir(path)

    pdfname_list = [
        filename for filename in filename_list if filename.endswith((".pdf", ".PDF"))]
    print(pdfname_list)
    for pdfname in pdfname_list:
        pdf_to_picture(path, pdfname)
    print("-------全部转换完成-------")


def pdf_to_picture(path, pdfname):
    pdfpath = os.path.join(path, pdfname)
    pdfDoc = fitz.open(pdfpath)
    pdf_pure_name = os.path.splitext(pdfname)[0]
    # imgDir = os.path.join(path, "picture", pdf_pure_name)
    imgDir = os.path.join(path, "jpg_picture")
    print("-------pdf %s 开始转换--------" % pdfname)
    for pg in range(pdfDoc.page_count):
        page = pdfDoc[pg]
        rotate = int(0)
        zoom_x = 2.5
        zoom_y = 2.5
        mat = fitz.Matrix(zoom_x, zoom_y).prerotate(rotate)
        pix = page.get_pixmap(matrix=mat, alpha=False)
        # 创建保存的文件夹
        if not os.path.exists(imgDir):
            os.makedirs(imgDir)

        imgpath = os.path.join(imgDir, pdf_pure_name + "-" + str(pg + 1) + ".png")
        pix._writeIMG(imgpath, 1)
        print("-------%s 完成--------" % (pdf_pure_name + "-" + str(pg + 1) + ".png"))
    print("-------pdf %s 转换完成--------" % pdfname)
    # 图片转成jpg
    convert_png()


if __name__ == '__main__':
    conver_to_picture()
